#!/bin/bash

# === 函数定义 ===

# 获取内存使用率百分比
get_memory_usage() {
    total=$(grep MemTotal /proc/meminfo | awk '{print $2}')
    free=$(grep MemFree /proc/meminfo | awk '{print $2}')
    buffers=$(grep Buffers /proc/meminfo | awk '{print $2}')
    cache=$(grep -m 1 '^Cache' /proc/meminfo | awk '{print $2}')

    used_kib=$((total - free - buffers - cache))
    usage_percent=$(awk "BEGIN {printf \"%.1f\", (${used_kib}/${total} * 100)}")
    echo "$usage_percent%"
}

# 获取磁盘根目录使用率
get_disk_usage() {
    df -h / | awk 'NR==2 {print $5}'
}

# 获取 named 进程信息
get_named_process_info() {
    if ! pgrep named > /dev/null; then
        echo "[named] 进程未运行"
        return
    fi

    for pid in $(pgrep named); do
        cpu_usage=$(ps -p "$pid" --no-headers -o %cpu | tr -d ' ')
        mem_usage=$(ps -p "$pid" --no-headers -o %mem | tr -d ' ')
        echo "[named PID: $pid] CPU 使用率: ${cpu_usage}%, 内存使用率: ${mem_usage}%"
    done
}

# === 主程序执行 ===
echo "=== DNS 虚拟机资源使用状态 ==="
echo "时间戳: $(date '+%Y-%m-%d %H:%M:%S')"
echo "内存使用率: $(get_memory_usage)"
echo "磁盘使用率: $(get_disk_usage)"
echo "named 进程信息:"
get_named_process_info